const CloudDBZoneWrapper = require('./CloudDBZoneWrapper')
const { defaultAvatar } = require('./consts')



const userHandler = async function (event, context, callback, logger) {
  logger.info('event入参', event.body)

  try {
    const cloudDBZoneWrapper = new CloudDBZoneWrapper(logger);
    const { action, payload } = JSON.parse(event.body || '{}')

    // 添加用户信息
    if (action === 'add') {
      await cloudDBZoneWrapper.add({
        ...payload,
        avatar: defaultAvatar
      })
      return callback({
        status: true
      })
    }

    // 修改用户信息
    if (action === 'patch') {
      await cloudDBZoneWrapper.patch(payload)
      return callback({
        status: true
      })
    }

    // 执行用户查询
    if (action === 'query') {
      const queryResult = await cloudDBZoneWrapper.query(payload);
      const userInfo = queryResult.map(a => Object.fromEntries(a.getFieldMap()))

      return callback({
        status: userInfo[0] ? true : false,
        data: userInfo[0] ?? null
      });
    }


    callback({
      status: false,
      errMsg: 'no valid action'
    })
  } catch (e) {
    // do something here
    callback({
      status: false,
      errMsg: e.message
    })
  }
};

export { userHandler };